<div class="panel panel-default">
  <div class="panel-heading">
    <h3 class="panel-title">报工审核</h3>
  </div>
  <div class="panel-body">
    <!-- 要审核的报工记录列表 -->
    <div class="alert alert-info">
      <h4>待审核的报工记录：</h4>
      {volist name="reports" id="report"}
      <div class="row" style="margin-bottom: 10px; padding: 10px; border: 1px solid #ddd; border-radius: 5px;">
        <div class="col-md-3">
          <strong>订单号：</strong>{$report.allocation.order.order_no}
        </div>
        <div class="col-md-3">
          <strong>产品：</strong>{$report.allocation.model.product.name} - {$report.allocation.model.name}
        </div>
        <div class="col-md-2">
          <strong>工序：</strong>{$report.allocation.process.name}
        </div>
        <div class="col-md-2">
          <strong>员工：</strong>{$report.user.nickname}
        </div>
        <div class="col-md-2">
          <strong>数量：</strong>{$report.quantity}
        </div>
      </div>
      {/volist}
    </div>
    
    <form id="audit-form" class="form-horizontal" role="form" data-toggle="validator" method="POST" action="">
      <div class="form-group">
        <label class="control-label col-xs-12 col-sm-2">审核状态:</label>
        <div class="col-xs-12 col-sm-8">
          <div class="radio">
            <label>
              <input type="radio" name="status" value="1" {if condition="!isset($status) || $status != '2'"}checked{/if}> 通过
            </label>
          </div>
          <div class="radio">
            <label>
              <input type="radio" name="status" value="2" {if condition="isset($status) && $status == '2'"}checked{/if}> 拒绝
            </label>
          </div>
        </div>
      </div>
      
      <div class="form-group" id="reason-group" style="display:none;">
        <label class="control-label col-xs-12 col-sm-2">拒绝原因:</label>
        <div class="col-xs-12 col-sm-8">
          <textarea name="reason" class="form-control" rows="3" placeholder="请输入拒绝原因"></textarea>
        </div>
      </div>
      
      <!-- 产品编号审核区域 -->
      {volist name="reports" id="report"}
        {if condition="$report.item_nos"}
          <div class="form-group">
            <label class="control-label col-xs-12 col-sm-2">产品编号审核:</label>
            <div class="col-xs-12 col-sm-8">
              <div class="alert alert-info">
                <strong>报工ID: {$report.id}</strong> - 计件工作，需要按产品编号分别审核
              </div>
              
              {php}
                $itemNos = json_decode($report['item_nos'], true);
                if (!$itemNos) $itemNos = [];
              {/php}
              
              {volist name="itemNos" id="itemNo"}
                <div class="item-audit-section" style="border: 1px solid #ddd; padding: 15px; margin-bottom: 15px; border-radius: 5px;">
                  <h5>产品编号: {$itemNo}</h5>
                  
                  <!-- 显示该产品编号的报工图片 -->
                  <div class="report-images" style="margin-bottom: 10px;">
                    <strong>报工图片:</strong>
                    {php}
                      $itemImages = \think\Db::name('scanwork_item_report_image')
                          ->alias('iri')
                          ->join('scanwork_product_item pi', 'iri.item_id = pi.id')
                          ->where('iri.report_id', $report['id'])
                          ->where('pi.item_no', $itemNo)
                          ->select();
                    {/php}
                    {volist name="itemImages" id="img"}
                      <div style="display: inline-block; margin: 5px;">
                        <a href="{$img.image_url}" target="_blank">
                          <img src="{$img.image_url}" style="width:80px;height:80px;object-fit:cover;border-radius:4px;">
                        </a>
                      </div>
                    {/volist}
                  </div>
                  
                  <!-- 审核图片上传 -->
                  <div class="audit-images">
                    <strong>审核图片:</strong>
                    <div class="form-group">
                      <div class="col-xs-12">
                        <input type="file" name="item_audit_files[{$report.id}][{$itemNo}][]" multiple accept="image/*" class="form-control" style="margin-bottom: 5px;">
                        <small class="help-block">可以选择多张图片，最多9张，单张≤10M</small>
                        <div id="preview-audit-{$report.id}-{$itemNo}" class="mt-2" style="display:flex;flex-wrap:wrap;gap:5px;min-height:50px;border:1px dashed #ccc;border-radius:5px;padding:10px;background:#f9f9f9;"></div>
                      </div>
                    </div>
                  </div>
                  
                  <!-- 审核视频上传 -->
                  <div class="audit-videos">
                    <strong>审核视频:</strong>
                    <div class="form-group">
                      <div class="col-xs-12">
                        <input type="file" name="item_audit_videos[{$report.id}][{$itemNo}][]" multiple accept="video/*" class="form-control" style="margin-bottom: 5px;">
                        <small class="help-block">可以选择多个视频文件，支持MP4、AVI、MOV、WMV、FLV、3GP、WEBM格式，单个文件≤100MB</small>
                        <div id="preview-audit-video-{$report.id}-{$itemNo}" class="mt-2" style="display:flex;flex-wrap:wrap;gap:5px;min-height:50px;border:1px dashed #ccc;border-radius:5px;padding:10px;background:#f9f9f9;"></div>
                      </div>
                    </div>
                  </div>
                </div>
              {/volist}
            </div>
          </div>
        {else}
          <!-- 计时工作的普通审核图片上传 -->
          <div class="form-group">
            <label class="control-label col-xs-12 col-sm-2">审核图片:</label>
            <div class="col-xs-12 col-sm-8">
              <div class="input-group">
                <input id="c-audit_images" class="form-control" size="50" name="audit_images" type="text" value="">
                <div class="input-group-addon no-border no-padding">
                  <span><button type="button" id="faupload-audit_images" class="btn btn-danger faupload" data-input-id="c-audit_images" data-mimetype="image/gif,image/jpeg,image/png,image/jpg,image/bmp,image/jfif" data-multiple="true" data-preview-id="p-audit_images"><i class="fa fa-upload"></i> {:__('Upload')}</button></span>
                  <span><button type="button" id="fachoose-audit_images" class="btn btn-primary fachoose" data-input-id="c-audit_images" data-mimetype="image/*" data-multiple="true"><i class="fa fa-list"></i> {:__('Choose')}</button></span>
                </div>
                <span class="msg-box n-right" for="c-audit_images"></span>
              </div>
              <ul class="row list-inline faupload-preview" id="p-audit_images"></ul>
            </div>
          </div>
          
          <!-- 计时工作的普通审核视频上传 -->
          <div class="form-group">
            <label class="control-label col-xs-12 col-sm-2">审核视频:</label>
            <div class="col-xs-12 col-sm-8">
              <input type="file" name="audit_videos[]" multiple accept="video/*" class="form-control" style="margin-bottom: 5px;">
              <small class="help-block">可以选择多个视频文件，支持MP4、AVI、MOV、WMV、FLV、3GP、WEBM格式，单个文件≤100MB</small>
              <div id="preview-audit-videos" class="mt-2" style="display:flex;flex-wrap:wrap;gap:5px;min-height:50px;border:1px dashed #ccc;border-radius:5px;padding:10px;background:#f9f9f9;"></div>
            </div>
          </div>
        {/if}
      {/volist}
      
      <div class="form-group" style="margin-top: 20px; text-align: center;">
        <div class="col-xs-12">
          <button type="submit" class="btn btn-success btn-lg" style="margin-right: 10px;">确定提交</button>
          <button type="reset" class="btn btn-default btn-lg">重置</button>
        </div>
      </div>
    </form>
  </div>
</div>

<!-- 图片放大查看模态框 -->
<div id="imageModal" style="display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.8);z-index:9999;cursor:pointer;" onclick="closeImageModal()">
    <div style="position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);text-align:center;">
        <img id="modalImage" style="max-width:90%;max-height:90%;border-radius:5px;box-shadow:0 0 20px rgba(0,0,0,0.5);" onclick="event.stopPropagation();">
        <div id="modalImageName" style="color:white;margin-top:10px;font-size:16px;"></div>
    </div>
</div>

<script>
    // 显示图片模态框
    function showImageModal(imageSrc, fileName) {
        document.getElementById('modalImage').src = imageSrc;
        document.getElementById('modalImageName').textContent = fileName;
        document.getElementById('imageModal').style.display = 'block';
    }
    
    // 关闭图片模态框
    function closeImageModal() {
        document.getElementById('imageModal').style.display = 'none';
    }
    
    // ESC键关闭模态框
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            closeImageModal();
        }
    });
// 确保jQuery可用
if (typeof $ === 'undefined' && typeof parent !== 'undefined' && parent.$) {
    $ = parent.$;
}

$(function() {
    console.log('审核页面JavaScript已加载');
    
    // 监听状态选择
    $('input[name="status"]').change(function() {
        console.log('状态选择改变:', $(this).val());
        if ($(this).val() == '2') {
            $('#reason-group').show();
            $('textarea[name="reason"]').attr('required', 'required');
        } else {
            $('#reason-group').hide();
            $('textarea[name="reason"]').removeAttr('required');
        }
    });
    
    // 初始化文件预览功能
    $('input[type="file"]').on('change', function() {
        console.log('文件选择改变');
        
        var $this = $(this);
        var files = this.files;
        console.log('选择的文件数量:', files.length);
        
        // 处理图片文件预览
        if ($this.attr('accept') && $this.attr('accept').includes('image/*')) {
            var $auditImages = $this.closest('.audit-images');
            var $preview = $auditImages.find('[id^="preview-audit-"]');
            
            console.log('找到图片预览容器:', $preview.length, $preview.attr('id'));
            
            if ($preview.length > 0) {
                $preview.empty();
                
                for (var i = 0; i < files.length && i < 9; i++) {
                    var file = files[i];
                    console.log('处理图片文件:', file.name, file.type);
                    
                    if (file.type.startsWith('image/')) {
                        var reader = new FileReader();
                        reader.onload = (function(file) {
                            return function(e) {
                                console.log('图片预览加载完成:', file.name);
                                $preview.append('<div style="display:inline-block;margin:5px;position:relative;border:2px solid #ddd;border-radius:5px;padding:2px;"><img src="' + e.target.result + '" style="width:120px;height:120px;object-fit:cover;border-radius:3px;cursor:pointer;" title="点击放大查看 - ' + file.name + '" onclick="showImageModal(\'' + e.target.result + '\', \'' + file.name + '\')"></div>');
                            };
                        })(file);
                        reader.readAsDataURL(file);
                    }
                }
            }
        }
        
        // 处理视频文件预览
        if ($this.attr('accept') && $this.attr('accept').includes('video/*')) {
            var $auditVideos = $this.closest('.audit-videos');
            var $preview = $auditVideos.find('[id^="preview-audit-video-"]');
            
            // 如果没有找到audit-videos容器，可能是普通审核视频
            if ($preview.length === 0) {
                $preview = $('#preview-audit-videos');
            }
            
            console.log('找到视频预览容器:', $preview.length, $preview.attr('id'));
            
            if ($preview.length > 0) {
                $preview.empty();
                
                for (var i = 0; i < files.length; i++) {
                    var file = files[i];
                    console.log('处理视频文件:', file.name, file.type);
                    
                    if (file.type.startsWith('video/')) {
                        var reader = new FileReader();
                        reader.onload = (function(file) {
                            return function(e) {
                                console.log('视频预览加载完成:', file.name);
                                var videoElement = '<video controls style="width:200px;height:150px;border-radius:3px;cursor:pointer;" title="' + file.name + '"><source src="' + e.target.result + '" type="' + file.type + '">您的浏览器不支持视频播放。</video>';
                                $preview.append('<div style="display:inline-block;margin:5px;position:relative;border:2px solid #ddd;border-radius:5px;padding:2px;">' + videoElement + '<div style="font-size:12px;text-align:center;margin-top:5px;color:#666;">' + file.name + '</div></div>');
                            };
                        })(file);
                        reader.readAsDataURL(file);
                    }
                }
            }
        }
    });
    
    // 表单提交
    $('#audit-form').on('submit', function(e) {
        e.preventDefault();
        console.log('表单提交');
        
        var formData = new FormData(this);
        var ids = '{$ids}';
        formData.append('ids', ids);
        
        // 处理产品编号审核文件
        $('input[name^="item_audit_files"]').each(function() {
            var files = this.files;
            if (files.length > 0) {
                var name = $(this).attr('name');
                for (var i = 0; i < files.length; i++) {
                    formData.append(name, files[i]);
                }
            }
        });
        
        // 处理普通审核视频文件
        $('input[name="audit_videos[]"]').each(function() {
            var files = this.files;
            if (files.length > 0) {
                for (var i = 0; i < files.length; i++) {
                    formData.append('audit_videos[]', files[i]);
                }
            }
        });
        
        // 处理产品编号审核视频文件
        $('input[name^="item_audit_videos"]').each(function() {
            var files = this.files;
            if (files.length > 0) {
                var name = $(this).attr('name');
                for (var i = 0; i < files.length; i++) {
                    formData.append(name, files[i]);
                }
            }
        });
        
        console.log('提交文件数量:', $('input[type="file"]').length);
        $('input[type="file"]').each(function() {
            console.log('文件输入:', $(this).attr('name'), '文件数量:', this.files.length);
        });
        
        $.ajax({
            url: '{:url("audit")}',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(res) {
                console.log('审核结果:', res);
                if (res.code == 1) {
                    // 显示成功消息
                    if (typeof Toastr !== 'undefined') {
                        Toastr.success(res.msg);
                    } else {
                        alert(res.msg);
                    }
                    
                    // 如果是弹窗模式，关闭弹窗并刷新父页面
                    if (parent && parent.Layer) {
                        parent.Layer.closeAll();
                        if (parent.table) {
                            parent.table.bootstrapTable('refresh');
                        }
                    } else {
                        setTimeout(function() {
                            location.reload();
                        }, 1000);
                    }
                } else {
                    if (typeof Toastr !== 'undefined') {
                        Toastr.error(res.msg);
                    } else {
                        alert(res.msg);
                    }
                }
            },
            error: function(xhr, status, error) {
                console.error('审核失败:', error);
                if (typeof Toastr !== 'undefined') {
                    Toastr.error('审核失败');
                } else {
                    alert('审核失败');
                }
            }
        });
    });
});


</script> 